<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig.timeLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig.memoryLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig.stackLimit ?? 0 }}
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="answer" title="答案">
            <a-card :style="{ width: '360px' }" title="这里是答案">
              <template #extra>
                <a-link>More</a-link>
              </template>
              <div>{{ answer }}</div>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="result" title="最近提交结果">
            <a-table :columns="columns" :data="mappedResults" />
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider size="0" />
        <a-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交代码
        </a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { onMounted, ref, watchEffect, withDefaults, defineProps } from "vue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest,
  QuestionSubmitVO,
  QuestionVO,
} from "../../../generated";
import { resultQuestionSubmitVO } from "../../../generated/models/resultQuestionSubmitVO";

interface Props {
  id: string;
}
// 定义一个新状态来存储答案
const answer = ref("");
const getAnswer = async () => {
  const res = await QuestionControllerService.getAnswerByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    answer.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const columns = ref([
  {
    title: "结果",
    dataIndex: "result",
    key: "result",
  },
  {
    title: "提交时间",
    dataIndex: "time",
    key: "time",
  },

  // 可以添加更多列...
]);
const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const results = ref<resultQuestionSubmitVO[]>([]);

// 创建计算属性来映射所需的字段
const mappedResults = computed(() => {
  return results.value.map((item) => ({
    result: item.judgeInfo, // 假设 judgeInfo 下有 description 字段
    time: item.createTime,
    // 嵌套字段访问
    // 映射其他需要的字段...
  }));
});
const getResults = async () => {
  try {
    const res = await QuestionControllerService.getQuestionResultByIdUsingGet(
      props.id as any
    );
    console.log("API Response Data:", res.data); // 打印从 API 获取的数据
    if (res && res.code === 0 && Array.isArray(res.data)) {
      results.value = res.data;
      console.log("Results State Value:", results.value); // 打印赋值后的状态
    } else {
      message.error("加载失败，" + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("Error fetching results:", error); // 打印错误信息
    message.error("获取结果时发生错误：");
  }
};

const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    question.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: "",
});

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
  } else {
    message.error("提交失败," + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  getResults();
  getAnswer(); // 页面加载时调用 getAnswer 方法
});

const changeCode = (value: string) => {
  form.value.code = value;
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
</style>
